﻿using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Utilities;
using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal.Networking;
using NLog;

namespace Casamiel.API.Infrastructure.Middlewares
{
    /// <summary>
    /// Response time middleware.
    /// </summary>
    public class ResponseTimeMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly NLog.ILogger logger = LogManager.GetLogger("ResponseTimeService");

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="T:Casamiel.API.Infrastructure.Middlewares.ResponseTimeMiddleware"/> class.
        /// </summary>
        /// <param name="next">Next.</param>
        public ResponseTimeMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// Invoke the specified context.
        /// </summary>
        /// <returns>The invoke.</returns>
        /// <param name="context">Context.</param>
        public async Task Invoke(HttpContext context)
        {

            //var begin = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            try
            {
                
                Stopwatch sw = new Stopwatch();
                sw.Start();
                await _next.Invoke(context).ConfigureAwait(false);
               // var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
                sw.Stop();

                logger.Trace($"ip:{context.Request.GetUserIp()},{context.Request.Path},执行时间{sw.ElapsedMilliseconds}毫秒,StatusCode:{context.Response.StatusCode}");

            }
            catch (AggregateException ex)
            {
                foreach (var item in ex.InnerExceptions)
                {
                    logger.Error(item.StackTrace);
                }
                logger.Error(ex.StackTrace);
            }


            // sw.Stop();

            // var begin = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);

            // logger.Trace($"ip:{context.Request.GetUserIp()},{context.Request.Path},执行时间{sw.ElapsedMilliseconds}毫秒,StatusCode:{context.Response.StatusCode}");

            //Console.WriteLine($"{context.Request.Path},nlog,执行时间{end-begin}毫秒");
        }
    }
}
